package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.CommunityComment;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by admin on 2019/8/13.
 */
@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private ITravelCommentRepository repository;


    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {
        if (!StringUtils.hasLength(comment.getId())) {
            comment.setCreateTime(new Date());
        }
        if (comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE) {
            Optional<TravelComment> optional = repository.findById(comment.getRefComment().getId());
            comment.setRefComment(optional.get());
        }

        repository.save(comment);
        return comment;
    }


    @Override
    public Page query(TravelCommentQuery qo) {

        Query query = new Query();
        if (qo.getTravelId() != -1) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        long count = template.count(query, TravelComment.class);
        if (count == 0) {
            return Page.empty();
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.by(Sort.Direction.DESC, "createTime"));

        query.with(pageable);

        List<TravelComment> list = template.find(query, TravelComment.class);

        return new PageImpl(list, pageable, count);
    }

    @Override
    public List<TravelComment> list() {

        Query query = new Query();
        query.limit(10).skip(0);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));

        List<TravelComment> list = template.find(query, TravelComment.class);
        return list;
    }


}
